package cn.teleware.util;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileInputStream;
import jcifs.smb.SmbFileOutputStream;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;

/**
 * samba共享文件操作工具
 *
 * @author :hongsw
 * @date :2020-11-16-14:42
 */
@Component
public class SambaUtil {

    /**
     * 共享文件夹地址
     */
    @Value("${samba.shareDirectory:/root}")
    private String shareDirectory;

    @Resource
    private NtlmPasswordAuthentication auth;

    /**
     * 发送文件到共享文件夹
     *
     * @param file 文件
     * @author hongsw
     * @date 2020/11/19 20:06
     **/
    public void sendBySamba(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        SmbFile remoteFile = new SmbFile(shareDirectory + "/" + fileName, auth);
        SmbFileOutputStream out = new SmbFileOutputStream(remoteFile);
        IOUtils.copy(file.getInputStream(), out);
        out.close();
        IOUtils.closeQuietly(out);
        IOUtils.closeQuietly(file.getInputStream());
    }


    /**
     * 下载文件
     *
     * @param fileName      要下载的名称
     * @param localFilePath 要下载本地的位置*
     * @author hongsw
     * @date 2020/11/19 20:20
     **/
    public void download(String fileName, String localFilePath) throws IOException {
        SmbFile remoteFile = new SmbFile(shareDirectory + "/" + fileName, auth);
        remoteFile.connect();
        FileUtils.copyInputStreamToFile(new SmbFileInputStream(remoteFile), new File(localFilePath));
    }


}
